function initializeProfileCompletion(){
	debugger;
	hideLoadingLayer();
	var formParts = [];
	$(".CPFCformPart").each(function(){
		var formPart = $(this);
		formParts.push(formPart.attr("id"));
	});


	$("#CPFCComplete").addClass("hideClass");
	var selectedFormPartId = "CPFCName";
	var nextInactive = false;
	var backInactive = true;
	var hideAllFromParts = function(){
		for(var i=0; i<formParts.length; i++){
			var formPart = $("#"+formParts[i]);
			formPart.addClass("hideClass").css("opacity","0");
		}
	};
	hideAllFromParts();
	$("#CPFCName").removeClass("hideClass");
	$("#CPFCName").css("opacity", "1");
	var activateNextBackButton = function(next){
		var buttonActive = "";
		
		if(next==="next"){
			buttonActive = $("#CPFCNext");
		}else{
			buttonActive = $("#CPFCBack");
		}
		buttonActive.removeClass("disabledButton");
	};
	var disableNextBackButton = function(next)
	{
		var buttonInactive = "";
		if(next==="next"){
			buttonInactive = $("#CPFCNext");
		}else{
			buttonInactive = $("#CPFCBack");
		}
		buttonInactive.addClass("disabledButton");
	};
	activateNextBackButton("next");
	disableNextBackButton("back");
	var doNextBack = function(whatToDo){
		var indexToDisplay = 0;
		var currentIndex = formParts.indexOf(selectedFormPartId);
		if(whatToDo === "next"){
			debugger;
			if(!nextInactive){
				hideAllFromParts();
				indexToDisplay = currentIndex + 1;
				var itemToDisplay = $("#"+formParts[indexToDisplay]);
				itemToDisplay.removeClass("hideClass");
				itemToDisplay.css("opacity", "1");
				selectedFormPartId = formParts[indexToDisplay];
				if(indexToDisplay + 1 >= formParts.length){
					nextInactive = true;
					disableNextBackButton("next");
					$("#CPFCNext").addClass("hideClass");
					$("#CPFCComplete").removeClass("hideClass");
				}
				backInactive = false;
				activateNextBackButton("back");
			}
		}else{
			if(!backInactive){
				debugger;
				hideAllFromParts();
				indexToDisplay = currentIndex - 1;
				var itemToDisplay = $("#"+formParts[indexToDisplay]);
				itemToDisplay.removeClass("hideClass");
				itemToDisplay.css("opacity", "1");
				selectedFormPartId = formParts[indexToDisplay];
				if(indexToDisplay - 1 < 0){
					backInactive = true;
					disableNextBackButton("back");
				}
				$("#CPFCComplete").addClass("hideClass");
				$("#CPFCNext").removeClass("hideClass");
				nextInactive = false;
				activateNextBackButton("next");
			}
		}
	};

	$("#CPFCNext").on("click", function(){
		doNextBack("next");
	});
	$("#CPFCBack").on("click", function(){
		doNextBack("back");
	});
	$("#CPFCComplete").on("click", function(){
		if(validateCompleteRegistrationForm()){
			debugger;	
			showLoadingLayer();		
			var responseFunction = function(r){
				hideLoadingLayer();
				debugger;
				r = JSON.parse(r);
				if(r && r.error){
					alert("There was an error. Please try again.");
				}
				else
				{
					var params = {
						action: "showProfile"
					};
					var url = getURL("profile.php");
					showLoadingLayer();
					$.post(url, params, displayProfile);
				}
			};
			var theForm = $("form[name='completeProfileForm']");
			var options = {
				success: responseFunction,
				resetForm: false
			};
			theForm.ajaxSubmit(options);
		}
	});

	initializePostcode("#postcode", "#address");

	initializeProfilePictureUploaders();

}
function validateCompleteRegistrationForm(){
	debugger;
	var message = "";
	var errMessages = [];
	errMessages.push(validateField("firstName", ["empty","textonly"]));
	errMessages.push(validateField("secondName", ["textonly"]));
	errMessages.push(validateField("firstLastname", ["empty","textonly"]));
	errMessages.push(validateField("secondLastname", ["textonly"]));
	errMessages.push(validateField("firstName", ["empty","textonly"]));
	errMessages.push(validateField("postcode", ["empty","postcode"]));
	errMessages.push(validateField("address", ["empty"]));
	errMessages.push(validateField("dateOfBirth", ["empty", "dateOfBirth"]));
	debugger;
	message = concatArray(message, errMessages);
	if(message.trim() !== ""){
		alert(message);
		return false;
	}
	return true;
}
function getAddress(postcode, outputFunction, coordsFunction){
	var result = "";
	$.post('http://maps.googleapis.com/maps/api/geocode/json?components=country:GB|postal_code:'+postcode+'&sensor=false', function(r) {
			debugger;
			if(!r['results'][0]){
				outputFunction("Please type your address here");
				return;
			}
			var lat = r['results'][0]['geometry']['location']['lat'];
			var lng = r['results'][0]['geometry']['location']['lng'];
			if(coordsFunction){
				coordsFunction(lat, lng);
			}
			$.post('http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+lng+'&sensor=false', function(address) {
				result = address['results'];
				/*result = address['results'][0]['address_components'][0]['long_name'];
				result += " " + address['results'][0]['address_components'][1]['long_name'];
				result += " " + address['results'][0]['address_components'][2]['long_name'];
				result += " " + address['results'][0]['address_components'][3]['long_name'];*/
				outputFunction(result);
			});
		});
	return result;
}
function initializePostcode(fieldId, addressFieldId){
	var addressId;
	if(addressFieldId){
		addressId = addressFieldId;
	}else
	{
		addressId = "#address";
	}

	var showAddress  = function(result){
		debugger;
		var resultStr = "";
		result = result[0]['address_components'];
		for(var i = 0; i<4; i++){
			resultStr += " " + result[i]['long_name'];
		}
		$(addressId).val(resultStr);
	};
	$(fieldId).on("change",function(){
			debugger;
			var postcode = $(this).val().trim();
			if(validatePostCode(postcode)){
				getAddress(postcode, showAddress);
			}else{
				alert("Not a valid postcode");
			}
	});
}

function showThumbnail(file,inputFileId)
{
    var previewerId = "#" + inputFileId + "Previewer";
    if (!file || !window.FileReader){
    	return; // no file selected, or no FileReader support
    } 

    if (/^image/.test( file.type)){ // only image file
        var reader = new FileReader(); // instance of the FileReader
        reader.readAsDataURL(file); // read the local file
			
        reader.onloadend = function(){ // set image data as background of div
            $(previewerId).css("background-image", "url("+this.result+")");
            $(previewerId).css("display", "block");
        }
    }else{
    }
}
function initializeProfilePictureUploaders(){
		$("input[type=file]").each(function (){
		$(this).on("change", function(event){
			debugger;
			var id = $(this).attr("id");
			var file = event.target.files[0];
			showThumbnail(file, id);			
		});

		});

		$("#CPFCPhotos > div a").each(function(){
			var thisObj = this;
			$(thisObj).on("click", function(){
				$(thisObj).next().trigger("click");
			});
		});
		debugger;
		$("#CPFCEditPhotos > div a").each(function(){
			var thisObj = this;
			$(thisObj).on("click", function(){
				$(thisObj).next().trigger("click");
			});
		});

		$("#uploadListingImageButton").each(function(){
			var thisObj = this;
			$(thisObj).on("click", function(){
				$(thisObj).next().trigger("click");
			});
		});
	}

function initializeEditProfile(r){
	var r = JSON.parse(r);
	if(!r || r.error){
		alert("There was an error. Please try again later");
	}
	hideLoadingLayer();
	configureListingAndProfileLayer(r);
	initializeProfilePictureUploaders();
	initializePostcode("#postcode", "#address");
	$("#CPFCExitEditProfile").on("click", function(){$("#profileButton").trigger("click");});
	var updateProfile = function()
	{
		if(validateCompleteRegistrationForm())
		{
			showLoadingLayer();
			var responseFunction = function(r){
				debugger;
				r = JSON.parse(r);
				if(r && r.error){
					alert("There was an error. Please try again.");
				}
				else
				{
					$("#profileButton").trigger("click");
				}
			};
			var theForm = $("form[name='editProfileForm']");
			var options = {
				success: responseFunction,
				resetForm: false
			};
			theForm.ajaxSubmit(options);
		}
	}
	$("#CPFCCompleteEdit").on("click", updateProfile);
}
function initializeProfile(){
	debugger;
	
	$("#editProfileButton").on("click", function(){
		showLoadingLayer();
		var url = getURL("profile.php");
		var params = {action : "getProfileEditor"};
		$.post(url, params, initializeEditProfile);
	});

	$("#createListingButton").on("click", function(){
		debugger;
		showLoadingLayer();
		var url = getURL("profile.php");
		var params = {action : "getListingEditor"};
		$.post(url, params, initializeListingEditor);
	});
}

function validateListingForm()
{
	return true;
}
function initializeListingEditorForm(){
	var currentDisplayedElement = $("#listingFormBody > div:first-child");
	var nextButton = $("#LEFCNext");
	var backButton = $("#LEFCBack");
	var completeButton = $("#LEFCComplete");
	var cancelButton = $("#LEFCCancel");
	var disabledButtonClass = "disabledButton";

	backButton.addClass(disabledButtonClass);
	var doNext = function()
	{
		debugger;
		var nextElement = currentDisplayedElement.next();
		if(nextElement.length != 0){
			showHideElement([currentDisplayedElement], false);
			showHideElement([nextElement], true);
			currentDisplayedElement = nextElement;
			backButton.removeClass(disabledButtonClass);
			if(nextElement.next().length == 0){
				showHideElement([nextButton], false);
				showHideElement([completeButton], true);
			}

		}
	};

	var doBack = function()
	{
		debugger;
		var backElement = currentDisplayedElement.prev();
		if(backElement.length != 0){
			showHideElement([currentDisplayedElement], false);
			showHideElement([backElement], true);
			currentDisplayedElement = backElement;
			showHideElement([nextButton], true);
			nextButton.removeClass(disabledButtonClass);
			showHideElement([completeButton], false);
			if(backElement.prev().length == 0){
				backButton.addClass(disabledButtonClass);
			}
		}
	};

	var doComplete = function()
	{
		alert("Validations in construction. I will submit the form anyways.");
		showLoadingLayer();
		var responseFunction = function(r){
			debugger;
			r = JSON.parse(r);
			if(r && r.error){
				alert("There was an error. Please try again.");
			}
			else
			{
				hideLoadingLayer();
				$("#profileButton").trigger("click");
			}
		};
		var theForm = $("#listingForm");
		var options = {
			success: responseFunction,
			resetForm: false
		};
		theForm.ajaxSubmit(options);

	};

	var doCancel = function()
	{

	};

	nextButton.on("click", doNext);
	backButton.on("click", doBack);
	completeButton.on("click", doComplete);
	cancelButton.on("click", function(){$("#profileButton").trigger("click");});
}
function initializeListingEditor(r){
	hideLoadingLayer();
	debugger;
	r = JSON.parse(r);
	if(!r || r.error){
		alert("There was an error. Please try again");
	}else{
		configureListingAndProfileLayer(r);
		initializeProfilePictureUploaders();
		initializeListingEditorForm();
		$("#typeofListing").on("change", displayForm);
		$("#typeofListing").trigger("change");
		$("#postcodeListing").on("change", function(){
			var displayDividedAddress = function(result){
				$("#coordsLatListing").val(result[1].geometry.location.lat);
				$("#coordsLngListing").val(result[1].geometry.location.lng);
				debugger;
				$("#cityListing").val(result[0]['address_components'][3]['long_name']);
				$("#areaListing").val(result[0]['address_components'][2]['long_name']);
				$("#streetNameListing").val(result[0]['address_components'][1]['long_name']);
				$("#houseNumberListing").val(result[0]['address_components'][0]['long_name']);
			};
			var postcode = $(this).val().trim();
			var saveCoords = function(lat, lng){
				$("#latitude").val(lat);
				$("#longitude").val(lng);
			}
			if(validatePostCode(postcode)){
				getAddress(postcode, displayDividedAddress, saveCoords);
			}else{
				alert("Not a valid postcode");
			}
		});
		//Here I initialize the options
	}
}
function displayProfile(r){
	debugger;
	hideLoadingLayer();
	r = JSON.parse(r);
	var error = false;
	if(!r || r.error){
		alert("There was an error. Please try again later");
	}else{
		configureLoginLayer(r);
		initializeProfile();
	}
};

var hiddenElements = [];
function displayForm(){
	debugger;
	displayListingElements(hiddenElements);
	clearArray(hiddenElements);
	var elementsToHide = [];
	var typeofListing = $(this).val();
	switch(typeofListing){
		case "1":
			elementsToHide = ["hotelRatingListing","hotelRulesListing", "openingTimeListing", "cancellationFeeListing"];
			break;
		case "2":
			elementsToHide = ["extraPeopleListing","houseRulesListing", "openingTimeListing","weekPriceListing", "monthPriceListing", "bedroomsListing", "cancellationFeeListing"];
			break;
		case "3":
			elementsToHide = ["roomTypeListing","bedTypeListing", "acomodatesListing", "bedroomsListing", "bedsListing",
			 "extraPeopleListing", "weekPriceListing", "monthPriceListing",
			 "cancellationListing", "cancellationFeeListing", "houseRulesListing", "hotelRulesListing",
			 "hotelRatingListing"];
			break;
		case "4":
			elementsToHide = ["roomTypeListing","bedTypeListing", "acomodatesListing", "bedroomsListing", "bedsListing",
			 "extraPeopleListing", "weekPriceListing", "monthPriceListing",
			 "cancellationListing", "cancellationFeeListing", "houseRulesListing", "hotelRulesListing",
			 "hotelRatingListing"];			
			 break;
		case "5":
			elementsToHide = ["roomTypeListing","bedTypeListing", "acomodatesListing", "bedroomsListing", "bedsListing",
			 "extraPeopleListing", "weekPriceListing", "monthPriceListing",
			 "cancellationListing", "cancellationFeeListing", "houseRulesListing", "hotelRulesListing",
			 "hotelRatingListing"];
			 break;
		default:
			$("#listingFormBody").addClass("hideClass");
			break;
	}
	hideElements(elementsToHide, false);
	if(typeofListing && typeofListing !== ""){
		$("#listingFormBody").removeClass("hideClass");;
	}
}

function hideElements(elementsToHide){
	for(var i = 0; i<elementsToHide.length; i++){
				hideListingFormElement(elementsToHide[i]);
	}
}
function hideListingFormElement(id){
	var label = $("label[for='"+id+"']");
	var element = $("#"+id);
	label.addClass("hideClass");
	element.addClass("hideClass");
	hiddenElements.push(id);
}

function displayListingElements(listingElementsToShow){
	for(var i = 0; i<listingElementsToShow.length; i++){
		showListingElement(listingElementsToShow[i]);
	}
}

function showListingElement(id){
	var label = $("label[for='"+id+"']");
	var element = $("#"+id);
	label.removeClass("hideClass");
	element.removeClass("hideClass");
}